<?php

namespace app\roomcall\controller;

use app\common\model\Users;
use app\common\model\Users as UserM;
use app\common\service\ViperCardService;
use think\Db;
use think\Validate;


class Login extends Home
{
    public $noNeedLogin = ['*'];

    /**
     * 获取房间信息
     */
    public function getRoom(){

        $data = $this->request->post();
        $rule = [
            'room_mac|房间设备' => 'require',
        ];
        // 定义验证提示
        $message = [
            'room_mac.require' => '房间设备MAC地址不能为空',
        ];
        $validate = new Validate($rule, $message);
        if (!$validate->check($data)) {
            $this->result($validate->getError(), '', 204);
        }

        $room_data = Db::name('qt_room')->where('clock_mac_path', $data['room_mac'])->find();
        if (empty($room_data)) {
            $this->result('设备还没有绑定房间', '', 204);
        }
        $result['room_data'] = $room_data;
        $result['store_data'] = Db::name('qt_store')->where('id', $room_data['store_id'])->find();

        $this->result('登录成功', $result, 200);
    }

    public function dologin()
    {
        if ($this->request->isPost()) {
            $data = $this->request->post();
            $rule = [
                'card_no|卡号' => 'require',
                'room_mac|房间设备' => 'require',
            ];
            // 定义验证提示
            $message = [
                'card_no.require' => '卡号不能为空',
                'room_mac.require' => '房间设备MAC地址不能为空',
            ];
            $validate = new Validate($rule, $message);
            if (!$validate->check($data)) {
                $this->result($validate->getError(), '', 204);
            }
            $card = substr($data['card_no'],2);
            $card = hexdec($card);
            $card = str_pad($card,10,0,STR_PAD_LEFT);
            $user_info = UserM::where('hand_card_neima', $card)->find();
            if ($user_info['status'] != 0) {
                $this->result('卡片已经被禁用，请联系管理员', '', 204);
            }
            if (empty($user_info)) {
                $this->result('没有找到卡号信息', '', 204);
            }
            $room_data = Db::name('qt_room')->where('clock_mac_path', $data['room_mac'])->find();
            if (empty($room_data)) {
                $this->result('设备还没有绑定房间', '', 204);
            }
            $token = token_rand();
            Db::name('qt_users')->where(['id'=>$user_info['id']])->update(['bell_token'=>$token]);
            $user_info['login_token'] = $token;
            $login_data['room_data'] = $room_data;
            $login_data['store_data'] = Db::name('qt_store')->where('id', $room_data['store_id'])->find();
            $login_data['user_data'] = $user_info;
            $this->result('登录成功', $login_data, 200);
        } else {
            $this->result('请求失败', '', 204);
        }
    }

}
